package cn.lyyb2001.blog.controller;

import cn.hutool.core.util.StrUtil;
import cn.lyyb2001.blog.entity.Category;
import cn.lyyb2001.blog.service.ICategoryService;
import cn.lyyb2001.common.model.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 * @author daiyb2
 * @Title: CategoriesController
 * @Description:
 * @date 2021/11/21 8:04
 **/
@RestController
@RequestMapping("/categories")
public class CategoriesController {
    @Autowired
    private ICategoryService categoryService;

    @GetMapping
    public Result<IPage<Category>> list() {
        IPage<Category> page = new Page<>();
        page.setRecords(categoryService.list());
        page.setTotal(categoryService.count());
        return Result.success(page);
    }


    @GetMapping("/list")
    public Result<IPage<Category>> list(Page<Category> page,
                       @RequestParam(required = false) String categoryName) {
        IPage<Category> result = categoryService.page(page,
                new LambdaQueryWrapper<Category>()
                        .like(StrUtil.isNotBlank(categoryName), Category::getCategoryName, categoryName));
        return Result.success(result);
    }

    //    @ApiOperation(value = "客户端详情")
//    @ApiImplicitParam(name = "clientId", value = "客户端id", required = true, paramType = "path", dataType = "String")
    @GetMapping("/{id}")
    public Result<Category> detail(@PathVariable String id) {
        Category client = categoryService.getById(id);
        return Result.success(client);
    }

    @PostMapping
    public Result add(@RequestBody Category category) {
        boolean status = categoryService.save(category);
        return Result.judge(status);
    }

    @PutMapping(value = "/{id}")
    public Result update(
            @PathVariable String id,
            @RequestBody Category category) {
        boolean status = categoryService.updateById(category);
        return Result.judge(status);
    }

    @DeleteMapping("/{ids}")
    public Result<Boolean> delete(@PathVariable("ids") String ids) {
        boolean status = categoryService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.judge(status);
    }

}
